package com.fausto.learnimprint.core.controller.impl

/**
 *
 *
 * 前端控制器
 *
 *
 * @author fausto
 * @since 2022-03-28
 */
import cn.hutool.core.util.StrUtil
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper
import com.fausto.learnimprint.core.controller.AnnouncementModule
import com.fausto.learnimprint.core.model.dto.CommonResult
import com.fausto.learnimprint.core.service.IAnnouncementService
import com.fausto.learnimprint.utils.FormatUtil
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime

@Api(tags = ["公告API"], basePath = "/announcements")
@RequestMapping("/announcements")
@RestController
class AnnouncementController : AnnouncementModule {

    @Autowired
    lateinit var announcementService: IAnnouncementService

    /**
     *      发布新公告
     */
    @ApiOperation(value = "发布公告")
    @PreAuthorize("hasAuthority('ADMIN')")
    @PostMapping
    override fun pubAnnouncement(
        @ApiParam(value = "标题", required = true, example = "示例标题")
        @RequestParam(required = true) title: String,
        @ApiParam(value = "内容", required = true, example = "示例公告内容")
        @RequestParam(required = true) body: String
    ): CommonResult<Any> {
        //判断参数是否合法
        return if (StrUtil.isBlank(title) || StrUtil.isBlank(body)) {
            CommonResult.fail("参数错误")
        } else if (title.length > 255) {
            CommonResult.fail("标题过长")
        } else try {
            //新增公告,默认不置顶
            announcementService.save(com.fausto.learnimprint.core.model.entity.Announcement().apply {
                announcementTitle = title
                announcementBody = body
                announcementTime = LocalDateTime.now()
            })
            CommonResult.ok("发布成功")
        } catch (e: Exception) {
            CommonResult.fail("操作失败", data = e.message)
        }
    }


    /**
     *      删除公告
     */
    @ApiOperation("删除公告")
    @PreAuthorize("hasAuthority('ADMIN')")
    @DeleteMapping("/{announcementId}")
    override fun deleteAnnouncement(
        @ApiParam(value = "公告ID", example = "1")
        @PathVariable
        announcementId: Int
    ): CommonResult<Any> {
        //判断ID是否合法
        return if (announcementId < 0) {
            CommonResult.fail("参数错误")
        } else try {
            //根据ID删除公告
            announcementService.removeById(announcementId)
            CommonResult.ok("删除成功")
        } catch (e: Exception) {
            CommonResult.fail("操作失败", data = e.message)
        }
    }


    /**
     *      更新公告置顶状态
     */
    @ApiOperation("公告置顶操作")
    @PreAuthorize("hasAuthority('ADMIN')")
    @PutMapping("/top/{announcementId}/{top}")
    override fun updateAnnouncement(
        @ApiParam(value = "公告ID", example = "1")
        @PathVariable announcementId: Int,
        @ApiParam(value = "是否置顶(0置顶,1不置顶)", example = "1")
        @PathVariable top: Int
    ): CommonResult<Any> {
        //top值不为0或1,或者公告ID小于0则返回错误
        return if (!FormatUtil.isIntRange(top) || announcementId < 0) {
            CommonResult.fail("参数错误")
        } else try {
            //进行置顶操作
            announcementService.update(UpdateWrapper<com.fausto.learnimprint.core.model.entity.Announcement?>().apply {
                eq("announcement_id", announcementId)
                set("announcement_top", top)
            })
            CommonResult.ok("置顶操作操作成功")
        } catch (e: Exception) {
            CommonResult.fail("操作失败", data = e.message)
        }
    }

    /**
     *      获取公告
     */
    @ApiOperation(value = "分页查询公告", notes = "页码+显示条数")
    @GetMapping("/{page}/{showCount}")
    override fun getAnnouncement(
        @ApiParam(value = "页面序号数", example = "1")
        @PathVariable
        page: Int,
        @ApiParam(value = "展示记录数", example = "5")
        @PathVariable
        showCount: Int
    ): CommonResult<Any> {
        return if (page < 1 || showCount < 1) {
            CommonResult.fail("参数错误")
        } else try {
            //通过MP的分页插件进行分页查询
            val records = announcementService.getCacheAnnouncement(page, showCount)
            CommonResult.ok("查询成功", data = records)
        } catch (e: Exception) {
            CommonResult.fail("操作失败", data = e.message)
        }
    }
}